package com.cameron.orderdemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

//import com.cameron.orderdemo.AddOrderActivity.ViewHolder;
import com.cameron.orderdemo.OrderDemoSettingsActivity;
import com.cameron.orderdemo.OrderDemoBatchActivity;

//import android.provider.Blacklist;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
//import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ViewAllOrderActivity extends Activity implements OnMenuItemClickListener, OnClickListener {

	private static final int ORDERDEMO_QUERY_TOKEN = 1024;
	private static final int ORDERDEMO_DELETE_TOKEN = 1025;
	private static final int ADD_ORDERDEMO = 0;
	private static final int EDIT_ORDERDEMO = 1;
	private static final int VIEW_ORDERDEMO = 2;

	private static final int MENU_EDIT = 0;
	private static final int MENU_REMOVE = 1;
	
	private static final int MENU_BATCH_OPRATION = 0;
	private static final int MENU_ADD_ORDER = 1;
	private static final int MENU_EXPORT = 2;
	private static final int MENU_SETTINGS = 3;

	private static final int REQUEST_CODE_EDIT_ORDER = 0;
	private static final int REQUEST_CODE_ADD_ORDER = 1;
	
	public static final String EXTERNAL_ROOT_DIR = Environment.getExternalStorageDirectory().getAbsolutePath();	
	public static final String DEFAULT_EXPORT_XSLFILE_DIR = EXTERNAL_ROOT_DIR + "/orderDemo/";
	public static final String DEFAULT_PHOTO_SAVE_DIR = EXTERNAL_ROOT_DIR + "/orderDemo/";
	public static final String SHARE_ORDERDEMO_SETTINGS = "shareOrderDemoSettings";
	public static final String SHARE_EXPORT_DIR = "shareExportDir";
	public static final String SHARE_PHOTO_DIR = "sharePhotoDir";	
	public static final String SHARE_TYPE_SETTINGS = "shareTypeSettings";	
	public static final String SHARE_UNIT_SETTINGS = "shareUnitSettings";	
	public static final String SHARE_COLOR_SETTINGS = "shareColorSettings";	
	public static final String SHARE_SIZE_SETTINGS = "shareSizeSettings";	
	public static final int SHARE_COUNT = 100;

	private OrderlistAllAdapter mCursorAdapter;
	private AsyncQueryHandler mQueryHandler;
	public static boolean exportThreadRunning = false;
	
	public static int mTotal = 0;
	public static int mCurrent = -1;

	GoodsInfo mCurGoodsInfo = new GoodsInfo();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.view_all_orders);

		ContentResolver cr = getContentResolver();
		Cursor c = cr.query(OrderDemo.CONTENT_URI, null, null, null, null);
		mCursorAdapter = new OrderlistAllAdapter(this, c);
		ListView listView = (ListView) findViewById(R.id.list);
		listView.setAdapter(mCursorAdapter);
		listView.setOnCreateContextMenuListener(this);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View v, int position, long id)
	        {
	            onListItemClick((ListView)parent, v, position, id);
	        }
	    });

		mQueryHandler = new BackgroundQueryHandler(getContentResolver());
		mQueryHandler.startQuery(ORDERDEMO_QUERY_TOKEN, null, OrderDemo.CONTENT_URI, null, null, null, null);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ADD_ORDERDEMO:
			    Intent intentAdd = new Intent(ViewAllOrderActivity.this, EditOrderActivity.class);
				startActivityForResult(intentAdd, REQUEST_CODE_ADD_ORDER);
			break;
		case EDIT_ORDERDEMO:
			    Intent intentEdit = new Intent(ViewAllOrderActivity.this, EditOrderActivity.class);
				Bundle boudle =new Bundle();
				boudle.putBoolean("ViewGoodInfo", false);
				boudle.putParcelable("GoodsInfo", mCurGoodsInfo);
				intentEdit.putExtras(boudle);
				startActivityForResult(intentEdit, REQUEST_CODE_EDIT_ORDER);
		    break;
		case VIEW_ORDERDEMO:
		        Intent intentView = new Intent(ViewAllOrderActivity.this, EditOrderActivity.class);
			    Bundle boudleView =new Bundle();
			    boudleView.putBoolean("ViewGoodInfo", true);
			    boudleView.putParcelable("GoodsInfo", mCurGoodsInfo);
			    intentView.putExtras(boudleView);
			    startActivityForResult(intentView, REQUEST_CODE_EDIT_ORDER);
	    break;
		}  
		
		return null;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		mCursorAdapter.changeCursor(null);
	}

	@Override
	protected void onResume() {
		super.onResume();
		mCursorAdapter.startRequestProcessing();
		TextView listInfo = (TextView) findViewById(R.id.textViewListInfo);
		HorizontalScrollView listItems = (HorizontalScrollView) findViewById(R.id.textViewListHead);
		listInfo.setText(R.string.order_list_info);
		if (mCursorAdapter.getCursor().getCount() == 0) {
			listInfo.setVisibility(View.VISIBLE);
			listItems.setVisibility(View.GONE);	
		} else {
			listInfo.setVisibility(View.GONE);	
			listItems.setVisibility(View.VISIBLE);
			OrderDemoActivity.mTotal = mCursorAdapter.getCursor().getCount();
			OrderDemoActivity.mCurrent = -1;
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		mCursorAdapter.stopRequestProcessing();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode != Activity.RESULT_OK) {
			return;
		}

		switch (requestCode) {
		case REQUEST_CODE_EDIT_ORDER:
			mQueryHandler.startQuery(ORDERDEMO_QUERY_TOKEN, null, OrderDemo.CONTENT_URI, null, null, null, null);
			break;
		default:
			break;
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
		Cursor c = mCursorAdapter.getCursor();
		String name = c.getString(c.getColumnIndex(OrderDemo.GOODS_NAME));
		menu.setHeaderTitle(name);

		//menu.add(0, MENU_EDIT, 0, R.string.edit).setOnMenuItemClickListener(this);
		menu.add(0, MENU_REMOVE, 0, R.string.remove).setOnMenuItemClickListener(this);
	}

	@Override
	public boolean onMenuItemClick(MenuItem item) {
		switch (item.getItemId()) {
		/*case MENU_EDIT:
			Cursor cr = mCursorAdapter.getCursor();
			mCurGoodsInfo._id = cr.getLong(cr.getColumnIndex(OrderDemo.ID));
			mCurGoodsInfo.market_name = cr.getString(cr.getColumnIndex(OrderDemo.MARKET_NAME));
			mCurGoodsInfo.store_name = cr.getString(cr.getColumnIndex(OrderDemo.STORE_NAME));
			mCurGoodsInfo.record_date_time = cr.getString(cr.getColumnIndex(OrderDemo.RECORD_DATE_TIME));
			mCurGoodsInfo.goods_type = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_TYPE));
			mCurGoodsInfo.goods_name = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_NAME));
			mCurGoodsInfo.measure_unit = cr.getString(cr.getColumnIndex(OrderDemo.MEARSURE_UNIT)); 
			mCurGoodsInfo.goods_color = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_COLOR));
			mCurGoodsInfo.goods_size = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_SIZE));
			mCurGoodsInfo.goods_price = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_PRICE));
			mCurGoodsInfo.goods_amount = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_AMOUNT));
			mCurGoodsInfo.delivery_date = cr.getString(cr.getColumnIndex(OrderDemo.DELIVERY_DATE));
			mCurGoodsInfo.goods_photo = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_PHOTO));
			mCurGoodsInfo.remarks = cr.getString(cr.getColumnIndex(OrderDemo.REMARKS));

			showDialog(EDIT_ORDERDEMO);

			return true;*/
		case MENU_REMOVE:
			Cursor c = mCursorAdapter.getCursor();
			long id = c.getLong(c.getColumnIndex(OrderDemo.ID));
			Uri url = Uri.withAppendedPath(OrderDemo.CONTENT_URI, String.valueOf(id));
			getContentResolver().delete(url, null, null);
			/*if (mCursorAdapter.getCursor().getCount() == 0) {
				TextView listInfo = (TextView) findViewById(R.id.textViewListInfo);
				listInfo.setVisibility(View.VISIBLE);
			} */
			return true;
		default:
			break;
		}

		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//menu.add(0, MENU_ADD_ORDER, 0, R.string.add_order);
		menu.add(0, MENU_EXPORT, 0, R.string.export);
		//menu.add(0, MENU_BATCH_OPRATION, 0, R.string.batch_operation);
		menu.add(0, MENU_SETTINGS, 0, R.string.settings);
		

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		Cursor c = mCursorAdapter.getCursor();
		if ((c.getCount() <= 0) || (exportThreadRunning)) {
			menu.findItem(MENU_EXPORT).setEnabled(false);
			//menu.findItem(MENU_BATCH_OPRATION).setEnabled(false);
		} else {
			menu.findItem(MENU_EXPORT).setEnabled(true);
			//menu.findItem(MENU_BATCH_OPRATION).setEnabled(true);
		}
		
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_EXPORT:
			ExportOrdersToXLS();
			break;
		case MENU_BATCH_OPRATION:
			// showConfirmDialog();
			Intent intent=new Intent(ViewAllOrderActivity.this, OrderDemoBatchActivity.class);
		    //intent.putExtra("isDel", true);
			startActivityForResult(intent, 3);
			break;
		case MENU_ADD_ORDER:
			System.out.println("MENU_ADD_NUMBER");
			showDialog(ADD_ORDERDEMO);
			break;
		case MENU_SETTINGS:
			Intent intentSettings = new Intent(ViewAllOrderActivity.this, OrderDemoSettingsActivity.class);
			startActivity(intentSettings);
			break;
		default:
			break;
		}

		return true;
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		mQueryHandler.startDelete(ORDERDEMO_DELETE_TOKEN, null, OrderDemo.CONTENT_URI, null, null);
	}
	
	void onListItemClick(ListView l, View view, int position, long id) {
		OrderDemoActivity.mCurrent = position;
		
		Cursor cr = mCursorAdapter.getCursor();
		mCurGoodsInfo._id = cr.getLong(cr.getColumnIndex(OrderDemo.ID));
		mCurGoodsInfo.market_name = cr.getString(cr.getColumnIndex(OrderDemo.MARKET_NAME));
		mCurGoodsInfo.store_name = cr.getString(cr.getColumnIndex(OrderDemo.STORE_NAME));
		mCurGoodsInfo.record_date_time = cr.getString(cr.getColumnIndex(OrderDemo.RECORD_DATE_TIME));
		mCurGoodsInfo.goods_type = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_TYPE));
		mCurGoodsInfo.goods_name = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_NAME));
		mCurGoodsInfo.measure_unit = cr.getString(cr.getColumnIndex(OrderDemo.MEARSURE_UNIT)); 
		mCurGoodsInfo.goods_color = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_COLOR));
		mCurGoodsInfo.goods_size = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_SIZE));
		mCurGoodsInfo.goods_price = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_PRICE));
		mCurGoodsInfo.goods_amount = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_AMOUNT));
		mCurGoodsInfo.delivery_date = cr.getString(cr.getColumnIndex(OrderDemo.DELIVERY_DATE));
		mCurGoodsInfo.goods_photo = cr.getString(cr.getColumnIndex(OrderDemo.GOODS_PHOTO));
		mCurGoodsInfo.remarks = cr.getString(cr.getColumnIndex(OrderDemo.REMARKS));
    	showDialog(VIEW_ORDERDEMO);
    }

	private void showConfirmDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle(R.string.warning);
		builder.setMessage(R.string.message_remove_all);
		builder.setPositiveButton(android.R.string.ok, this);
		builder.setNegativeButton(android.R.string.cancel, null);
		builder.show();
	}

	private class OrderlistAllAdapter extends CursorAdapter implements Runnable {
		private LayoutInflater myInflater;
		private LinkedList<GoodsInfo> mOrdersList = new LinkedList<GoodsInfo>();
		private Thread mQueryThread;
		private boolean mDone;
		private Cursor c;
		public Map<Integer, Boolean> isck;

		public OrderlistAllAdapter(Context context, Cursor c) {

			super(context, c);
			this.c = c;
			myInflater = LayoutInflater.from(context);
			isck = new HashMap<Integer, Boolean>();
			for (int i = 0; i < c.getCount(); i++) {
				isck.put(i, false);
			}

		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			//TextView tvName = (TextView) view.findViewById(R.id.goods_name);
			//String name = cursor.getString(cursor.getColumnIndex(OrderDemo.GOODS_NAME));
		    //tvName.setText(name);
			((TextView) view.findViewById(R.id.market_name))
			    .setText(cursor.getString(cursor.getColumnIndex(OrderDemo.MARKET_NAME)));
			((TextView) view.findViewById(R.id.store_name))
		        .setText(cursor.getString(cursor.getColumnIndex(OrderDemo.STORE_NAME)));
			((TextView) view.findViewById(R.id.record_date_time))
	        	.setText(cursor.getString(cursor.getColumnIndex(OrderDemo.RECORD_DATE_TIME)));
			((TextView) view.findViewById(R.id.goods_type))
	        	.setText(cursor.getString(cursor.getColumnIndex(OrderDemo.GOODS_TYPE)));
			((TextView) view.findViewById(R.id.goods_name))
	        	.setText(cursor.getString(cursor.getColumnIndex(OrderDemo.GOODS_NAME)));
			((TextView) view.findViewById(R.id.measure_unit))
	        	.setText(cursor.getString(cursor.getColumnIndex(OrderDemo.MEARSURE_UNIT)));
			((TextView) view.findViewById(R.id.goods_color))
	        	.setText(cursor.getString(cursor.getColumnIndex(OrderDemo.GOODS_COLOR)));
			((TextView) view.findViewById(R.id.goods_size))
	        	.setText(cursor.getString(cursor.getColumnIndex(OrderDemo.GOODS_SIZE)));
			((TextView) view.findViewById(R.id.goods_price))
	        	.setText(cursor.getString(cursor.getColumnIndex(OrderDemo.GOODS_PRICE)));
			((TextView) view.findViewById(R.id.goods_amount))
	        	.setText(cursor.getString(cursor.getColumnIndex(OrderDemo.GOODS_AMOUNT)));
			((TextView) view.findViewById(R.id.delivery_date))
	        	.setText(cursor.getString(cursor.getColumnIndex(OrderDemo.DELIVERY_DATE)));
			((TextView) view.findViewById(R.id.rmarks))
	        	.setText(cursor.getString(cursor.getColumnIndex(OrderDemo.REMARKS)));
			//((TextView) view.findViewById(R.id.goods_name))
	        	//+.setText(cursor.getString(cursor.getColumnIndex(OrderDemo.GOODS_NAME)));
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(context);

			return inflater.inflate(R.layout.view_all_orders_items, parent, false);
		}

		public void startRequestProcessing() {
			mDone = false;
			mQueryThread = new Thread(this);
			mQueryThread.setPriority(Thread.MIN_PRIORITY);
			mQueryThread.start();
		}

		public void stopRequestProcessing() {
			mDone = true;
			if (mQueryThread != null) {
				mQueryThread.interrupt();
			}
		}

		@Override
		public void run() {
			while (!mDone) {
				GoodsInfo ci = null;
				synchronized (mOrdersList) {
					if (mOrdersList.isEmpty()) {
						try {
							mOrdersList.wait(1000);
						} catch (InterruptedException ie) {
							// Ignore and continue processing requests
						}
					} else {
						ci = mOrdersList.removeFirst();
					}
				}
			}
		}
	}

	private class BackgroundQueryHandler extends AsyncQueryHandler {

		public BackgroundQueryHandler(ContentResolver cr) {
			super(cr);
		}

		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {

			switch (token) {
			case ORDERDEMO_QUERY_TOKEN:
				mCursorAdapter.changeCursor(cursor);
				break;
			default:
				break;
			}
		}
	}

    private void ExportOrdersToXLS() {
    	new Thread(new Runnable() {
            public void run() {
            	exportThreadRunning = true;
            	//Time t=new Time("GMT+8"); //Time Zone
            	Time t=new Time();
            	t.setToNow();            	
            	//String fileName = "/mnt/sdcard/"+System.currentTimeMillis()+".xls";
                
                SharedPreferences shareOrderDemoSettings = getSharedPreferences(OrderDemoActivity.SHARE_ORDERDEMO_SETTINGS, 0);   
                String exportDirectoryPath = shareOrderDemoSettings.getString(OrderDemoActivity.SHARE_EXPORT_DIR, 
                		OrderDemoActivity.DEFAULT_EXPORT_XSLFILE_DIR); 
                if (!exportDirectoryPath.endsWith("/"))
                	exportDirectoryPath = exportDirectoryPath + "/";

            	new File(exportDirectoryPath).mkdirs();//cameron need to change.
            	String fileName = exportDirectoryPath + t.year+"." + (t.month+1)+"." + t.monthDay+"."
            			          + "_" + t.hour+"." + t.minute+"." + t.minute + ".xls";
        		Cursor c = mCursorAdapter.getCursor();
        		if (null != c) {
        			c.moveToFirst();
        		} else {
        			c.close();
        			return;
        		}
        		GoodsInfo[] goodsInfo = new GoodsInfo[c.getCount()];
        		int index = 0;
        		while ((null != c) && (index < c.getCount())) {
        			goodsInfo[index] = new GoodsInfo();
        			goodsInfo[index]._id = c.getLong(c.getColumnIndex(OrderDemo.ID));
        			goodsInfo[index].market_name = c.getString(c.getColumnIndex(OrderDemo.MARKET_NAME));
        			goodsInfo[index].store_name = c.getString(c.getColumnIndex(OrderDemo.STORE_NAME));
        			goodsInfo[index].record_date_time = c.getString(c.getColumnIndex(OrderDemo.RECORD_DATE_TIME));
        			goodsInfo[index].goods_name = c.getString(c.getColumnIndex(OrderDemo.GOODS_NAME));
        			goodsInfo[index].measure_unit = c.getString(c.getColumnIndex(OrderDemo.MEARSURE_UNIT)); 
        			goodsInfo[index].goods_color = c.getString(c.getColumnIndex(OrderDemo.GOODS_COLOR));
        			goodsInfo[index].goods_size = c.getString(c.getColumnIndex(OrderDemo.GOODS_SIZE));
        			goodsInfo[index].goods_price = c.getString(c.getColumnIndex(OrderDemo.GOODS_PRICE));
        			goodsInfo[index].goods_amount = c.getString(c.getColumnIndex(OrderDemo.GOODS_AMOUNT));
        			goodsInfo[index].delivery_date = c.getString(c.getColumnIndex(OrderDemo.DELIVERY_DATE));
        			goodsInfo[index].goods_photo = c.getString(c.getColumnIndex(OrderDemo.GOODS_PHOTO));
        			goodsInfo[index].remarks = c.getString(c.getColumnIndex(OrderDemo.REMARKS));
        			
        			c.moveToNext();
        			index ++;
        		}
            	//boolean rt = new ExcelOperation().writeExcel(goodsInfo, fileName);
            	boolean rt = ExcelOperation.writeExcel(goodsInfo, fileName);
            	Message msg = new Message();
            	if (!rt) {
            		//Toast.makeText(getApplicationContext(), R.string.exportError, Toast.LENGTH_LONG).show();
            		msg.arg1 = R.string.exportError;
            		showMessage.sendMessage(msg);
            		System.out.print(R.string.exportError);
            	} else {
            		//Toast.makeText(getApplicationContext(), R.string.exportSuccess, Toast.LENGTH_LONG).show();
            		msg.arg1 = R.string.exportSuccess;
            		showMessage.sendMessage(msg);
            		System.out.print(R.string.exportSuccess);
            	}   
            	exportThreadRunning = false;
            }
        }, "exportOrders").start();
    }
    
    private Handler showMessage = new Handler() {

    	@Override
    	public void handleMessage(Message msg) {
    	    super.handleMessage(msg);
		    Toast.makeText(getApplicationContext(), msg.arg1, Toast.LENGTH_LONG).show();
    	}

    };
}